//
//  ArticleDetailViewController.m
//  OneDay
//
//  Created by lanou3g on 15/11/1.
//  Copyright © 2015年 oneDay. All rights reserved.
//

#import "ArticleDetailViewController.h"
#import "ArticleDetailModel.h"
#import "ArticleDetailTableViewCell.h"
#import "LoginViewController.h"

@interface ArticleDetailViewController ()

@property (nonatomic, strong) ArticleDetailModel *model;

@end

@implementation ArticleDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 没有数据的时候为白色，没有线条
    self.tableView.separatorStyle = NO;
    
    [self addShareAndCollection];
    
    NSString *needURL = [kArticleDetailUrl stringByAppendingString:[NSString stringWithFormat:@"%@", self.needID]];
    [self requestArticleDetailDataWithUrl:needURL block:^() {
        [self addHeaderAndFooter];
        [self.tableView reloadData];
    }];
    
    [self addBackButton];
}
// 添加返回按钮
- (void)addBackButton
{
    UIBarButtonItem *leftB = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-reply-3.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBar:)];
    self.navigationItem.leftBarButtonItem = leftB;
}
- (void)backBar:(UIBarButtonItem *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}




#pragma mark -- 添加分享，收藏按钮
- (void)addShareAndCollection
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 0, kWidth - 0.19 * kWidth, 0.06 * kHeight)];
    NSArray *array = @[@"heart_shape_small_on", @"ic_nav_share_black"];
    for (int i = 0; i < 2; i++) {
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        button.frame = CGRectMake(kWidth - 0.34 * kWidth + i * 0.09 * kWidth, 0.011 * kHeight, 0.067 * kWidth, 0.037 * kHeight);
        [button setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        [button setImage:[UIImage imageNamed:array[i]] forState:(UIControlStateNormal)];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        button.tag = i + 200;
        [view addSubview:button];
    }
    self.navigationItem.titleView  = view;
    
    
    // 创建返回左键
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonItem:)];
    self.navigationItem.leftBarButtonItem = left;
}

// 分享收藏按钮方法
- (void)buttonAction:(UIButton *)sender
{
    if (sender.tag == 200) {
        UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:nil message:@"收藏成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        DataManager *manager = [DataManager shareManager];
        // 判断是否登录
        if ([manager isLogin] == NO) {
            
            LoginViewController *loginVC = [[LoginViewController alloc] init];
            
            // 实现block
            loginVC.block = ^void(){
                NSLog(@"登录成功");
            };
            
            UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:loginVC];
            [self presentViewController:navC animated:YES completion:nil];
        }else{
            LeanCloudObject *leanCloud = [[LeanCloudObject alloc] init];
            NSString *userName = [manager userName];
            NSLog(@"%@", userName);
            // 先判断是否收藏过
            NSArray *articleArray = [leanCloud selectStundetWithStyle:@"article" userName:userName];
            BOOL isHave = NO;
            for (ArticleObject *article in articleArray) {
                if ([article.title isEqualToString:self.model.title]) {
                    isHave = YES;
                    break;
                }
            }
            if (isHave == NO) {
                [leanCloud creatObjectWithTitle:self.model.title imageUrl:@"" needString:self.needID style:@"article" userName:userName];
                [alertView show];
            }else{
                alertView.message = @"您已经收藏过了";
                [alertView show];
            }
            // 实现 2 秒回收
            [self performSelector:@selector(actionAlert:) withObject:alertView afterDelay:2];
        }
        
    }else{
        
        // 需要分享的文字
        NSString *str = [NSString stringWithFormat:@"OneDay推荐：每日推荐十篇美文,最喜欢这一篇了《%@》，详情请下载APP OneDay 阅读", self.model.title];
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"56396d0ee0f55aff4d0010a0"
                                          shareText:str
                                         shareImage:nil
                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent, UMShareToDouban,UMShareToEmail,UMShareToFacebook, nil]
                                           delegate:nil];
    }
}
#pragma mark -- 实现2秒消失
- (void)actionAlert:(UIAlertView *)alertView
{
    [alertView dismissWithClickedButtonIndex:0 animated:YES];// 三秒回收
}



// 返回方法
- (void)leftBarButtonItem:(UIBarButtonItem *)buttonSender
{
    [self.navigationController popViewControllerAnimated:YES];
}

// 添加表头、表尾
- (void)addHeaderAndFooter
{
    OneDayObject *oneObject = [[OneDayObject alloc] init];
    
    //  设置 总的(整个tableView的)表头
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 100)];
    headerView.tag = 1000000;
    
    // 布置表头
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, kWidth - 10, 50)];
    titleLabel.font = [UIFont systemFontOfSize:18];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = [NSString stringWithFormat:@"%@", self.model.title];
    [headerView addSubview:titleLabel];
    
    UILabel *authorLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, titleLabel.bottom, 230, 30)];
    authorLabel.text = [NSString stringWithFormat:@"——作者:%@", self.model.author];
    authorLabel.font = [UIFont systemFontOfSize:14];
    [headerView addSubview:authorLabel];
    
    UILabel *readCountLabel = [[UILabel alloc] initWithFrame:CGRectMake(kWidth - 105, titleLabel.bottom, 100, 30)];
    readCountLabel.text = [NSString stringWithFormat:@"||阅读量:%@", self.model.times];
    readCountLabel.font = [UIFont systemFontOfSize:14];
    [headerView addSubview:readCountLabel];
    
    CGFloat height1 = [oneObject sizeWithText:self.model.summary font:15 width:kWidth - 20 height:10000].height;
    UILabel *summaryLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, authorLabel.bottom, kWidth - 20, height1 + 20)];
    summaryLabel.backgroundColor = [UIColor colorWithRed:242.55 / 255.0 green:244.87 / 255.0 blue:236.52 / 255.0 alpha:1];
    summaryLabel.layer.cornerRadius = summaryLabel.frame.size.width / 10;
    summaryLabel.text = [NSString stringWithFormat:@"%@", self.model.summary];
    summaryLabel.font = [UIFont systemFontOfSize:15];
    summaryLabel.numberOfLines = 0;
    [headerView addSubview:summaryLabel];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, summaryLabel.bottom + 10, kWidth - 10, 20)];
    label.text = @"—— 正文 ——";
    label.font = [UIFont systemFontOfSize:15];
    label.textAlignment = NSTextAlignmentCenter;
    [headerView addSubview:label];
    
    // 改变表头的高度
    headerView.frame = CGRectMake(0, 0, kWidth, label.bottom + 10);
    self.tableView.tableHeaderView = headerView;
    
    //  设置 总的(整个tableView的)表尾
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 100)];
    
    self.tableView.tableFooterView = footerView;
    
    UILabel *footerLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 100, 40)];
    footerLabel1.text = [NSString stringWithFormat:@"%@", self.model.author];
    [footerView addSubview:footerLabel1];
    
    UILabel *footerLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(5, footerLabel1.bottom, kWidth - 10, 60)];
    footerLabel2.numberOfLines = 0;
    footerLabel2.text = [NSString stringWithFormat:@"%@", self.model.authorbrief];
    [footerView addSubview:footerLabel2];
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ArticleDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ArticleDetailTableViewCell"];
    if (cell == nil) {
        cell = [[ArticleDetailTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"ArticleDetailTableViewCell"];
    }
    // 取消选中的颜色
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    if (self.model != nil) {
        cell.model = self.model;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OneDayObject *oneObject = [[OneDayObject alloc] init];
    return [oneObject sizeWithText:self.model.text font:12 width:kWidth - 0.08 * kWidth height:100000].height;
}


- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}

#pragma mark -- 请求数据
- (void)requestArticleDetailDataWithUrl:(NSString *)url block:(void (^)())block
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
        [request setHTTPMethod:@"GET"];
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            // 保护方法
            if (data == nil) {
                return ;
            }
            NSDictionary *rootDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
            self.model = [[ArticleDetailModel alloc] init];
            [self.model setValuesForKeysWithDictionary:rootDictionary];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                block();
            });
        }];
        [dataTask resume];
    });
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
